package com.seqb.common.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.extra.mail.MailUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.seqb.common.config.SeqbConfig;
import com.seqb.common.utils.RedisUtils;
import com.seqb.utils.DateUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lilinshen
 * @title 开课吧爬取视频任务
 * @description 请填写相关描述
 * @date 2020/11/10
 */
public class KekeiBaJob implements Job {
    private static final Logger LOGGER = LoggerFactory.getLogger(KekeiBaJob.class);
    public HttpHeaders headers = new HttpHeaders();

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SeqbConfig seqbConfig;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            headers = new HttpHeaders();
            Object taskParams = redisUtils.get("taskParams");
            String courseIds = "";
            String emails = "";
            if (null != taskParams) {
                JSONArray parseArray = JSON.parseArray(taskParams.toString());
                for (int i = 0; i < parseArray.size(); i++) {
                    JSONObject item = parseArray.getJSONObject(i);
                    String type = item.getString("type");
                    if ("KekeiBaJob".equals(type)) {
                        JSONArray value = item.getJSONArray("value");
                        for (int j = 0; j < value.size(); j++) {
                            JSONObject jsonObject = value.getJSONObject(j);
                            if (jsonObject.getString("key").equals("courseIds")) {
                                courseIds = jsonObject.getString("value");
                            } else if (jsonObject.getString("key").equals("emails")) {
                                emails = jsonObject.getString("value");
                            } else {
                                headers.add(jsonObject.getString("key"), jsonObject.getString("value"));
                            }
                        }
                    }
                }
            }
            LOGGER.info("开课吧爬取视频任务开始-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            taskList(courseIds, emails);
            LOGGER.info("开课吧爬取视频任务结束-----------" + DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void taskList(String courseIds, String emails) {
        //获取accessToken的值
        String accessToken = "";
        String requestUrl = "https://weblearn.kaikeba.com/get/bsy_video/access_token";
        HttpMethod httpMethod = HttpMethod.GET;
        Map<String, Object> paramsMap = new HashMap<>();
        HttpEntity httpEntity = new HttpEntity(paramsMap, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
        HttpStatus status = responseEntity.getStatusCode();
        if (status.equals(HttpStatus.OK)) {
            String entityBody = responseEntity.getBody();
            entityBody = StringEscapeUtils.unescapeJava(entityBody);
            JSONObject result = JSON.parseObject(entityBody);
            JSONObject data = (JSONObject) result.get("data");
            //accessToken的值
            accessToken = data.getString("access_token");
        }
        if (StrUtil.isEmpty(accessToken)) {
            LOGGER.info("开课吧爬取视频任务,-----------,accessToken获取失败!");
            return;
        }
        String prePath = seqbConfig.getUploadPath() + "kaikeba/" + DateUtil.format(new Date(), "yyyy-MM-dd");
        String[] split = courseIds.split(",");
        for (int a = 0; a < split.length; a++) {
            int total = 1;
            String course_id = split[a];
            requestUrl = "https://weblearn.kaikeba.com/student/courseinfo?course_id=" + course_id;
            httpMethod = HttpMethod.GET;
            paramsMap = new HashMap<>();
            httpEntity = new HttpEntity(paramsMap, headers);
            responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String entityBody = responseEntity.getBody();
                entityBody = StringEscapeUtils.unescapeJava(entityBody);
                JSONObject result = JSON.parseObject(entityBody);
                String code = result.getString("code");
                if(!code.equals("1")){
                    MailUtil.send("lilinshen@cecjx.com", "开课吧爬取视频任务", "开课吧爬取视频任务失败，token失效。", true);
                    break;
                }

                JSONObject data = (JSONObject) result.get("data");
                //课程名称
                String course_name = data.getString("course_name");

                //保存到文件里面
                String path = prePath + "/" + course_name + "/章节目录.txt";
                String batPath = prePath + "/" + course_name + "/一键下载视频.bat";
                FileUtil.del(path);
                FileUtil.del(batPath);
                FileUtil.appendUtf8String(course_name + FileUtil.getLineSeparator(), new File(path));//1

                //课程章节
                JSONArray chapter_list = data.getJSONArray("chapter_list");
                for (int i = 0; i < chapter_list.size(); i++) {
                    JSONObject item = chapter_list.getJSONObject(i);
                    //第几章节
                    String rank_num = item.getString("rank_num");
                    //章节名称
                    String chapter_name = item.getString("chapter_name");
                    //章节id
                    String chapter_id = item.getString("chapter_id");

                    String textStr = "    第" + rank_num + "章 " + chapter_name;
                    FileUtil.appendUtf8String(textStr + FileUtil.getLineSeparator(), new File(path));//2

                    //2.获取章节视频
                    requestUrl = "https://weblearn.kaikeba.com/student/chapterinfo?course_id=" + course_id + "&chapter_id=" + chapter_id;
                    responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);

                    status = responseEntity.getStatusCode();
                    if (status.equals(HttpStatus.OK)) {
                        String entityBody1 = responseEntity.getBody();
                        entityBody1 = StringEscapeUtils.unescapeJava(entityBody1);
                        JSONObject result1 = JSON.parseObject(entityBody1);
                        JSONObject data1 = (JSONObject) result1.get("data");
                        JSONArray section_list = data1.getJSONArray("section_list");
                        for (int j = 0; j < section_list.size(); j++) {
                            JSONObject item1 = section_list.getJSONObject(j);
                            //第几节
                            String rank_num1 = item1.getString("rank_num");
                            String section_name1 = item1.getString("section_name");
                            textStr = "        第" + rank_num1 + "节 " + section_name1;
                            FileUtil.appendUtf8String(textStr + FileUtil.getLineSeparator(), new File(path));//3

                            JSONArray group_list = item1.getJSONArray("group_list");
                            for (int k = 0; k < group_list.size(); k++) {
                                JSONObject item2 = group_list.getJSONObject(k);
                                JSONArray content_list = item2.getJSONArray("content_list");

                                for (int l = 0; l < content_list.size(); l++) {
                                    JSONObject item3 = content_list.getJSONObject(l);
                                    String content_title = item3.getString("content_title");
                                    String content_type = item3.getString("content_type");
                                    JSONArray content = item3.getJSONArray("content");

                                    textStr = "           " + content_title;
                                    FileUtil.appendUtf8String(textStr + FileUtil.getLineSeparator(), new File(path));//4

                                    //表示资料
                                    if ("6".equals(content_type)) {
                                        for (int n = 0; n < content.size(); n++) {
                                            JSONObject item4 = content.getJSONObject(n);
                                            String url = item4.getString("url");
                                            textStr = "               " + "资料地址" + (n + 1) + ":" + url;
                                            FileUtil.appendUtf8String(textStr + FileUtil.getLineSeparator(), new File(path));//5
                                        }
                                    } else {
                                        //视频key
                                        JSONObject item4 = content.getJSONObject(0);
                                        String callback_key = item4.getString("callback_key");
                                        if (StringUtils.isNotEmpty(callback_key)) {
                                            //获取真实的视频地址
                                            requestUrl = "https://api-vod.baoshiyun.com/vod/v1/platform/media/detail?mediaId=" + callback_key + "&accessToken=" + accessToken;
                                            responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
                                            status = responseEntity.getStatusCode();
                                            if (status.equals(HttpStatus.OK)) {
                                                String entityBody2 = responseEntity.getBody();
                                                entityBody2 = StringEscapeUtils.unescapeJava(entityBody2);
                                                JSONObject result2 = JSON.parseObject(entityBody2);
                                                JSONObject data2 = (JSONObject) result2.get("data");
                                                JSONObject mediaMetaInfo = (JSONObject) data2.get("mediaMetaInfo");
                                                JSONArray videoGroup = mediaMetaInfo.getJSONArray("videoGroup");
                                                for (int m = 0; m < videoGroup.size(); m++) {
                                                    JSONObject item5 = videoGroup.getJSONObject(m);
                                                    String resolution = item5.getString("resolution");
                                                    String playURL = item5.getString("playURL");
                                                    textStr = "               " + "视频地址：" + resolution + ":" + playURL;
                                                    if (resolution.equals("超清")) {
                                                        FileUtil.appendUtf8String(textStr + FileUtil.getLineSeparator(), new File(path));//6

                                                        String batStr = "ffmpeg.exe -i " + playURL + " " + total + "-" + content_title.replaceAll(" ", "") + ".mp4";
                                                        FileUtil.appendString(batStr + FileUtil.getLineSeparator(), new File(batPath), CharsetUtil.CHARSET_GBK);//7
                                                        //需要另保存为ANSI格式
                                                        total++;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //拷贝ffmpeg.exe文件
                String srcPath = seqbConfig.getUploadPath() + "kaikeba/";
                FileUtil.copy(new File(srcPath + "ffmpeg.exe"), new File(prePath + "/" + course_name + "/ffmpeg.exe"), true);
            }
        }

        //压缩文件夹
        String srcPath = prePath;
        String zipPath = prePath + ".zip";
        FileUtil.del(zipPath);
        ZipUtil.zip(srcPath, zipPath);

        //发送邮件通知别人去下载
        String fileName = "/kaikeba/" + DateUtil.format(new Date(), "yyyy-MM-dd") + ".zip";
        String downloadUrl = "http://192.168.4.54:8083/seqb/file" + fileName;

        split = emails.split(",");
        for (int a = 0; a < split.length; a++) {
            String email = split[a];
            MailUtil.send(email, "开课吧爬取视频任务", "开课吧爬取视频任务，下载链接：" + downloadUrl, true);
        }
    }
}
